package com.cll.printdemo;

import android.accessibilityservice.AccessibilityServiceInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.accessibility.AccessibilityManager;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.print.PrintHelper;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    private Button mBtCc;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        startService(new Intent(this,MyAccessibilityService.class));

        if (!isAccessibilityEnabled()) {
            Toast.makeText(this, "无障碍服务未启动！", Toast.LENGTH_SHORT).show();
            gotoSetting();
        }
    }
    public void gotoSetting() {
        Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
    private void initView() {
        mBtCc = findViewById(R.id.bt_cc);
        mBtCc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                doPrintPictures();
            }
        });
    }

    /**系统打印机--打印图片*/
    private void doPrintPictures() {
        PrintHelper photoPrinter = new PrintHelper(this);
        photoPrinter.setScaleMode(PrintHelper.SCALE_MODE_FIT);
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.abc); //本地图片
        photoPrinter.printBitmap("droids.jpg - test print", bitmap, new PrintHelper.OnPrintFinishCallback() {
            @Override
            public void onFinish() {
                Log.d("cllstudy", "onFinish() called");
                Toast.makeText(MainActivity.this, "打印完成", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 判断无障碍服务是否启动
     * @return
     */
    public boolean isAccessibilityEnabled() {
        String localServiceStr = new ComponentName(getPackageName(), MyAccessibilityService.class.getName()).flattenToShortString();
        AccessibilityManager accessibilityManager = (AccessibilityManager) getSystemService(Context.ACCESSIBILITY_SERVICE);
        List<AccessibilityServiceInfo> accessibilityservices = accessibilityManager.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_GENERIC);
        for (AccessibilityServiceInfo info : accessibilityservices) {
            if (localServiceStr.equals(info.getId())) {
                return true;
            }
        }
        return false;
    }
}